<template>
  <div>
    <a-modal
      title="试听课"
      :visible="visible"
      :footer="null"
      @cancel="visible = false"
      :width="1700"
      style="top: 140px;"
    >
      <!-- @ok="handleOk"
      -->
      <a-row :gutter="48">
        <a-col :md="8" :sm="24">
          所在校区：
          <a-select
            v-model="queryParma.structures_id"
            placeholder="请选择校区"
            allowClear
            style="width:80%;"
          >
            <a-select-option
              v-for="(item,index) in structureList"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-col>
        <a-col :md="8" :sm="24">
          所属课程：
          <a-select
            v-model="queryParma.course_id"
            style="width:80%;"
            placeholder="请选择所属课程"
            @change="$forceUpdate()"
            allowClear
          >
            <a-select-option
              v-for="(item,index) in courseSelect"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-col>
        <a-col :md="8" :sm="24">
          上课教师：
          <a-select
            v-model="queryParma.teacher_id"
            style="width:80%;"
            placeholder="请选择上课教师"
            allowClear
            @change="$forceUpdate()"
          >
            <a-select-option
              v-for="(item,index) in teacherSelect"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-col>
      </a-row>
      <div class="action_button">
        <a-button @click="getLastWeek">上一周</a-button>
        <a-date-picker
          v-model="queryParma.date"
          class="datePicker"
          format="YYYY-MM-DD"
          @change="$forceUpdate()"
          show-time
        />
        <!-- :disabled-date="disabledDate"
        :disabled-time="disabledDateTime"-->
        <a-button @click="getNextWeek">下一周</a-button>
      </div>
      <a-spin :spinning="loading">
        <a-tabs :default-active-key="1" @change="callback" style="margin-top:10px;">
          <a-tab-pane :key="1" tab="跟班试听">
            <div class="timeTable">
              <div class="table_head">
                <div></div>
                <div
                  class="weekNum"
                  v-for="(item,index) in data.title"
                  :key="index"
                >{{item.weekName}}({{item.date}})</div>
              </div>
              <div class="table_body">
                <div class="table_body_line" v-for="(item,index) in data.week" :key="index">
                  <div class="teacher_name">{{item.name}}</div>
                  <div class="having_class" v-for="(j,k) in item.classInfo" :key="k">
                    <div class="classInfoLine" v-for="(m,n) in j" :key="n">
                      <a-popover placement="rightTop" arrowPointAtCenter>
                        <template slot="content">
                          <div class="orderNAMEinfo" style="overflow:hidden !important;">
                            <p
                              class="popoverTag"
                              style="color:rgb(51,51,51);"
                            >所在校区：{{m.structure_name}}</p>
                            <p class="popoverTag" style="color:rgb(51,51,51);">班级：{{m.class}}</p>
                            <p
                              class="popoverTag"
                              style="color:rgb(51,51,51);"
                            >上课时间：{{m.date}}&nbsp;&nbsp;{{m.time_interval}}</p>
                            <p class="popoverTag" style="color:#888">
                              <a-icon
                                :component="classing"
                                style="margin-right:5px; color:#bfbfbf;font-size:16px;"
                              ></a-icon>
                              课程：{{m.course}}
                            </p>
                            <p class="popoverTag" style="color:#888">
                              <a-icon
                                :component="classing"
                                style="margin-right:5px; color:#bfbfbf;font-size:16px;"
                              ></a-icon>
                              老师：
                              {{m.teachers.toString()}}
                            </p>
                            <p class="popoverTag" style="color:#888">
                              <a-icon
                                :component="classroom"
                                style="margin-right:5px; color:#bfbfbf;font-size:16px;"
                              ></a-icon>
                              教室：{{m.field_name}}
                            </p>

                            <p class="popoverTag" style="color:#888">
                              <a-icon
                                type="team"
                                style="margin-right:5px; color:#bfbfbf;font-size:16px;"
                              />
                              学生人数：{{m.student.length}}
                            </p>
                            <div class="popoverBtmLine">
                              <a @click="arrangeAudition(m,j)" v-if="m.type=='schedule'">跟班试听</a>
                            </div>
                            <div class="alreadyOrderName" v-if="m.type=='call'">
                              <img src="~@/assets/orderName.png" alt />
                            </div>
                            <div
                              class="alreadyOrderName"
                              v-else-if="m.type!=='call'&&m.class_id==0"
                            >
                              <img src="~@/assets/tryListen.png" alt />
                            </div>
                          </div>
                        </template>
                        <a-button
                          class="button__"
                          :style="{color:'white', background:m.color==0?'rgb(120, 191, 250)':m.color==1?'rgb(250, 187, 124)':m.color==2?'rgb(152, 217, 139)':m.color==3?'rgb(66, 214, 195)':m.color==4?'rgb(245, 146, 200)':m.color==5?'rgb(182, 161, 245)':'',
                    }"
                        >
                          <span v-if="m.class">{{m.class}}</span>
                          <span v-if="m.time_interval">，</span>
                          <span v-if="m.time_interval">{{m.time_interval}}</span>
                        </a-button>
                      </a-popover>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane :key="2" tab="一对一试听">
            <div class="timeTable">
              <div class="table_head">
                <div></div>
                <div
                  class="weekNum"
                  v-for="(item,index) in data.title"
                  :key="index"
                >{{item.weekName}}({{item.date}})</div>
              </div>
              <div class="table_body">
                <div class="table_body_line" v-for="(item,index) in data.week" :key="index">
                  <div class="teacher_name">{{item.name}}</div>
                  <div class="having_class" v-for="(j,k) in item.classInfo" :key="k">
                    <div class="classInfoLine1by1" v-for="(m,n) in j" :key="n">
                      <span class="firstSpan">
                        <span v-if="m.class">{{m.class}}</span>
                        <span v-if="m.time_interval">，</span>
                        <span>{{m.time_interval||''}}</span>
                      </span>
                    </div>
                    <div class="create1by1" v-if="is_show(k)" @click="createNew(item,k)">
                      <div>新增试听</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <a-modal
              title="添加试听课"
              :visible="visible1by1"
              @ok="handleOk('formRule')"
              @cancel="visible1by1=false"
            >
              <a-form-model
                ref="formRule"
                :model="form"
                :rules="formRules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
              >
                <a-spin :spinning="loading">
                  <a-form-model-item label="选择校区" prop="structures_id">
                    <a-select
                      v-model="form.structures_id"
                      placeholder="请选择校区"
                      @change="changeSelect('structure')"
                    >
                      <a-select-option
                        v-for="(item,index) in schoolSelect"
                        :key="index"
                        :value="item.id"
                      >{{item.name}}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="课程名称" prop="course_id">
                    <a-select
                      :disabled="!form.structures_id"
                      v-model="form.course_id"
                      :placeholder="!form.structures_id?'请先选择校区':'请选择课程'"
                    >
                      <a-select-option
                        v-for="(item,index) in courseSelect"
                        :key="index"
                        :value="item.id"
                        v-if="item.type==1"
                      >{{item.name}}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="上课日期" prop="start_time">
                    <a-date-picker
                      v-model="form.start_time"
                      placeholder="请选择上课日期"
                      @change="changeDate"
                      :disabled-date="disabledDate"
                      :allowClear="false"
                    />
                  </a-form-model-item>
                  <a-form-model-item label="上课时间" prop="class_time_id">
                    <a-select
                      placeholder="请选择上课时间"
                      style="width: 200px"
                      v-model="form.class_time_id"
                      @change="changeTime(form.class_time_id)"
                    >
                      <a-select-option
                        v-for="(item,index) in classTimeSelect"
                        :key="index"
                        :value="item.id"
                      >{{item.start_time}}&nbsp;~&nbsp;{{item.end_time}}</a-select-option>
                    </a-select>
                    <a @click="showChild('classTime')" style="margin-left:10px;">设置</a>
                  </a-form-model-item>
                  <a-form-model-item label="上课老师" prop="teacher_id">
                    <a-select
                      v-model="form.teacher_id"
                      :disabled="!form.start_time||!form.class_time_id"
                      :placeholder="!form.class_time_id?'请选择上课时间':'请选择上课老师'"
                      option-label-prop="label"
                    >
                      <a-select-option
                        v-for="(item,index) in teacherFilter"
                        :key="index"
                        :value="item.id"
                        :label="item.name"
                      >
                        {{item.name}}
                        <span style="color:red;float:right;" v-if="item.free_status">冲突</span>
                        <span style="float:right;" v-else>空闲</span>
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="上课教室">
                    <a-select
                      :placeholder="!form.structures_id?'请先选择校区':'请选择上课教室'"
                      style="width: 200px"
                      allowClear
                      v-model="form.classroom_id"
                    >
                      <a-select-option :value="0">不指定</a-select-option>
                      <a-select-option
                        v-for="(item,index) in classroomSelect"
                        :key="index"
                        :value="item.id"
                      >{{item.name}}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="上课内容">
                    <a-textarea
                      v-model="form.content"
                      placeholder="请输入上课内容"
                      :auto-size="{ minRows: 3, maxRows: 5 }"
                    />
                  </a-form-model-item>
                </a-spin>
              </a-form-model>
            </a-modal>
            <class-time ref="classTime" @reload="getSelect"></class-time>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { lessonTableTimeList, add1By1, addTryListen } from '@/api/lessonTable'
import { coursesList, newCoursesList } from '@/api/courseCharge'
import { teacherList } from '@/api/teacher'
import { classTimeList } from '@/api/classTime'
import classTime from '@/components/classTimeModel'
import { classroom, classing } from '@/core/icons'
import { classroomList } from '@/api/classroom'
import { campusList } from '@/api/structure'
import moment from 'moment'
export default {
  name: 'listenLessonTable',
  components: { classTime },
  props: ['student_id', 'list_id'],
  data() {
    return {
      classroom,
      classing,
      loading: false,
      data: {
        title: [],
        week: [],
      },
      visible: false,
      visible1by1: false,
      queryParma: {
        date: moment(),
        school_id: this.$store.state.user.school,
        api_type: 2,
        class_type: 2,
      },
      schoolSelect: [],
      courseSelect: [],
      teacherSelect: [],
      teacherFilter: [],
      classTimeSelect: [],
      classroomSelect: [],
      structureList: [],
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        course_id: undefined,
        student_id: undefined,
        teacher_id: undefined,
        class_time_id: undefined,
        start_time: '',
        structures_id: undefined,
        classroom_id: 0,
        // moment('2018-12-12')
        content: '',
        school_id: this.$store.state.user.school,
      },
      formRules: {
        structures_id: [{ required: true, message: '请选择校区', trigger: 'change' }],
        course_id: [{ required: true, message: '请选择课程', trigger: 'change' }],
        teacher_id: [{ required: true, message: '请选择上课老师', trigger: 'change' }],
        class_time_id: [{ required: true, message: '请选择上课时间段', trigger: 'change' }],
        start_time: [{ required: true, message: '请选择上课日期', trigger: 'change' }],
      },
    }
  },
  created() {
    let today = this.formatTime()
    this.queryParma.date = moment(today)
    this.getSelect(2)
  },
  computed: {
    is_show() {
      return function (index) {
        let d = new Date(this.data.title[index].date).getTime() / 1000
        let t = parseInt(new Date().getTime() / 1000) - 86400
        return d >= t ? true : false
      }
    },
  },
  watch: {
    queryParma: {
      handler(newName, oldName) {
        this.getTableList()
      },
      //immediate:true代表如果在 wacth 里声明了obj之后，就会立即先去执行里面的handler方法，
      immediate: true,
      deep: true, // 开启深度监听，默认是false
    },
  },
  methods: {
    changeSelect(type) {
      if (type == 'structure') {
        this.loading = true
        newCoursesList({
          structures_id: this.form.structures_id,
          school_id: this.$store.state.user.school,
          pageSize: 9999999999,
          type: 1
          
        }).then((res) => {
          let arr = []
          res.data.forEach((val) => {
            arr.push(val.id)
          })
          if (arr.indexOf(this.form.course_id) == -1) {
            this.form.course_id = undefined
          }
          this.courseSelect = res.data
          this.loading = false
        })
        classroomList({
          school_id: this.$store.state.user.school,
          pageSize: 999999999,
          structures_id: this.form.structures_id,
        }).then((res) => {
          this.classroomSelect = res.data
        })
      }
    },
    //选择当前时间之后
    disabledDate(current) {
      return current && current < moment().startOf('day')
    },
    disabledDateTime() {
      return {
        disabledHours: () => this.range(0, 24).splice(4, 20),
        disabledMinutes: () => this.range(30, 60),
        disabledSeconds: () => [55, 56],
      }
    },
    //选择当前时间之后
    getLastWeek() {
      let newDay = moment(this.queryParma.date).format('YYYY-MM-DD')
      let lastWeekDay = new Date(new Date(newDay).getTime() - 168 * 60 * 60 * 1000)
      let theRealDay = this.formatTime(lastWeekDay)
      this.queryParma.date = moment(theRealDay)
    },
    getNextWeek() {
      let newDay = moment(this.queryParma.date).format('YYYY-MM-DD')
      let nextWeekDay = new Date(new Date(newDay).getTime() + 168 * 60 * 60 * 1000)
      let theRealDay = this.formatTime(nextWeekDay)
      this.queryParma.date = moment(theRealDay)
    },
    getTableList() {
      this.loading = true
      let param = JSON.parse(JSON.stringify(this.queryParma))
      param.date = moment(param.date).format('YYYY-MM-DD')
      lessonTableTimeList(param)
        .then((res) => {
          this.loading = false
          this.data = res
        })
        .catch((err) => {
          this.loading = false
          if (err) {
            this.$message.error(err.data.message || '获取数据失败，请刷新后重试')
          } else {
            this.$message.error('获取数据失败，请刷新后重试')
          }
        })
    },
    getMonday(date) {
      //获取周一日期
      let dd = new Date(date)
      let week = dd.getDay()
      let minus = week ? week - 1 : 6
      dd.setDate(dd.getDate() - minus)
      let y = dd.getFullYear()
      let m = dd.getMonth() + 1
      let d = dd.getDate()
      return y + '-' + m + '-' + d
    },
    formatTime(e) {
      let date
      if (e) {
        date = new Date(e)
      } else {
        date = new Date()
      }
      let seperator1 = '-'
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      let today = year + seperator1 + month + seperator1 + strDate
      return today
    },
    showVisible() {
      this.visible = true
    },
    arrangeAudition(e) {
      let that = this
      let monday = this.getMonday(e.time)
      this.$confirm({
        title: '提示',
        content:
          '是否将同学安排进入' +
          `${e.course ? '【' + e.course + '】' : ''}` +
          `${e.date ? e.date : ''}` +
          `${e.week ? '（' + e.week + '）' : ''}` +
          `${e.time_interval_name ? e.time_interval_name : ''}` +
          `${e.time_interval ? e.time_interval : ''}` +
          '课次试听？',
        okText: '是',
        okType: 'primary',
        cancelText: '否',
        onOk() {
          that.visible = false
          addTryListen({
            school_id:that.$store.state.user.school,
            student_id: that.student_id,
            id: that.list_id ? that.list_id : undefined,
            schedules_id: e.id,
            date: monday,
            start_time: e.time,
          })
            .then((res) => {
              that.$message.success('安排试听成功')
              that.getTableList()
              that.$router.push({ name: 'student_Info', query: { id: that.student_id } })
            })
            .catch((err) => {
              that.$message.error(err.data.message || '跟班试听失败~')
              that.getTableList()
            })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    createNew(j, index) {
      this.form.start_time = moment(this.data.title[index].date)
      this.visible1by1 = true
    },
    handleOk(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = JSON.parse(JSON.stringify(this.form))
          param.start_time = moment(param.start_time).format('YYYY-MM-DD')
          this.classTimeSelect.forEach((val) => {
            if (val.id == param.class_time_id) {
              param.class_start_time = val.start_time
              param.class_end_time = val.end_time
              delete param.class_time_id
            }
          })
          param.student_id = this.student_id
          if (this.list_id) {
            param.id = this.list_id
          }
          add1By1(param)
            .then((res) => {
              this.$message.success('安排试听成功')
              this.getTableList()
              this.form = {
                course_id: undefined,
                student_id: undefined,
                teacher_id: undefined,
                class_time_id: undefined,
                start_time: '',
                structures_id: undefined,
                classroom_id: 0,
                // moment('2018-12-12')
                content: '',
                school_id: this.$store.state.user.school,
              }
              this.$router.push({ name: 'student_Info', query: { id: this.student_id, childType: 2 } })
            })
            .catch((err) => {
              this.$message.error(err.data.message || '添加失败')
            })
        } else {
          return false
        }
      })
    },
    getSelect(e = 2) {
      campusList({
        school_id: this.$store.state.user.school,
        type: 1,
      }).then((res) => {
        this.structureList = res
      })
      campusList({ school_id: this.$store.state.user.school })
        .then((res) => {
          this.schoolSelect = res
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取校区列表失败')
        })
      coursesList({ school_id: this.$store.state.user.school,is_enable: 1, pageSize: 99999999 }).then((res) => {
        this.courseSelect = res.data
      })
      teacherList({ school_id: this.$store.state.user.school, pageSize: 9999999 })
        .then((res) => {
          this.teacherSelect = res.data
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取教师列表失败')
        })
      classTimeList({ school_id: this.$store.state.user.school, pageSize: 99999999 }).then((res) => {
        this.classTimeSelect = res.data
      })
    },
    callback(key = 1) {
      if (key == 1) {
        this.queryParma = {
          date: moment(),
          school_id: this.$store.state.user.school,
          api_type: 2,
          class_type: 2,
        }
      } else {
        this.queryParma = {
          date: moment(),
          school_id: this.$store.state.user.school,
        }
      }
      this.getSelect(key)
      this.queryParma.course_id = undefined
      this.queryParma.teacher_id = undefined
    },
    showChild(e) {
      if (e == 'classTime') {
        this.$refs.classTime.showModal()
      }
    },
    changeDate(date, dateString) {
      if (this.form.class_time_id) {
        this.form.teacher_id = undefined
        let sTime
        let eTime
        this.classTimeSelect.forEach((val) => {
          if (val.id == this.form.class_time_id) {
            sTime = val.start_time
            eTime = val.end_time
          }
        })
        this.getTeacherFilter(dateString, sTime, eTime)
      }
    },
    changeTime(time) {
      if (this.form.start_time) {
        this.form.teacher_id = undefined
        let sTime
        let eTime
        let dateString = moment(this.form.start_time).format('YYYY-MM-DD')
        this.classTimeSelect.forEach((val) => {
          if (val.id == time) {
            sTime = val.start_time
            eTime = val.end_time
          }
        })
        this.getTeacherFilter(dateString, sTime, eTime)
      }
    },
    getTeacherFilter(dateString, sTime, eTime) {
      this.loading = true
      teacherList({
        school_id: this.$store.state.user.school,
        start_time: dateString,
        class_start_time: sTime,
        class_end_time: eTime,
        pageSize: 999999999,
      })
        .then((res) => {
          this.teacherFilter = res.data
        })
        .catch((err) => {
          this.$message.error('获取上课教师列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>
<style lang="less">
.ant-popover-inner-content {
  padding: 0;
}
</style>
<style lang="less" scoped>
.orderNAMEinfo {
  padding-top: 20px;
  position: relative;
  .popoverTag {
    font-size: 14px;
    margin-bottom: 8px;
    padding: 0 20px;
  }

  .alreadyOrderName {
    position: absolute;
    top: -1px;
    right: -1px;
  }
}
.ant-popover-inner-content {
  padding: 0;
}
.popoverBtmLine {
  margin-top: 10px;
  border-top: 1px solid #e8e8e8;
  min-width: 300px;
  padding: 10px;
  line-height: 24px;
  text-align: center;
  display: flex;
  font-size: 16px;
  font-weight: 500;
  justify-content: space-around;
}
.action_button {
  width: 100%;
  text-align: center;
  .datePicker {
    margin: 0 10px;
  }
  margin: 20px 0 0;
}
.timeTable {
  margin: 15px;
  // border: 1px solid #e8e8e8;
  .table_head {
    // border-bottom: 1px solid #e8e8e8;
    display: flex;
    div {
      padding: 5px 0;
    }
    .weekNum {
      width: 220px;
      text-align: center;
      // border-left: 1px solid #e8e8e8;
    }
    div:first-child {
      width: 100px;
    }
  }
  .table_body {
    .table_body_line {
      display: flex;
      // border-bottom: 1px solid #e8e8e8;
      height: 80px;
      div {
        text-align: center;
      }
      .teacher_name {
        width: 100px;
        line-height: 80px;
      }
      .having_class {
        width: 220px;
        padding: 15px 0px;
        height: 80px;
        overflow: hidden;
        overflow-y: auto;
        // border-left: 1px solid #e8e8e8;
        position: relative;
        .classInfoLine {
          margin: 0 10px 5px;

          .button__ {
            display: block !important;
            max-width: 190px;
            height: 20px;
            font-size: 12px;
            border-radius: 2px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        .classInfoLine1by1 {
          margin: 0 10px 5px;
          .firstSpan {
            display: block !important;
            max-width: 190px;
            height: 20px;
            font-size: 12px;
            border-radius: 2px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            background: #ccc;
            color: white;
          }
        }
        .create1by1 {
          width: 217px;
          height: 80px;
          position: absolute;
          top: 0;
          left: 0;
          display: none;
          text-align: center;
          background: rgba(24, 144, 255, 0.8);
          line-height: 80px;
          color: white;
          div {
            cursor: pointer;
          }
        }
      }
      .having_class:hover {
        .create1by1 {
          display: block;
        }
      }
    }
    .table_body_line:last-child {
      border-bottom: none;
    }
  }
}
</style>
